package com.zlict.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zlict.admin.domain.Project;
import com.zlict.admin.domain.ProjectAndProjectApproval;
import com.zlict.admin.domain.ProjectApproval;
import com.zlict.admin.domain.ProjectMember;
import com.zlict.admin.mapper.ProjectApprovalMapper;
import com.zlict.admin.mapper.ProjectMapper;
import com.zlict.admin.mapper.ProjectMemberMapper;
import com.zlict.admin.service.IProjectService;
import com.zlict.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

import static com.zlict.common.utils.SecurityUtils.getUserId;

/**
 * 项目基本信息Service业务层处理
 *
 * @author dzw
 * @date 2025-06-06
 */
@Service
public class ProjectServiceImpl implements IProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectApprovalMapper projectApprovalMapper;
    @Autowired
    private ProjectMemberMapper projectMemberMapper;


    /**
     * 查询项目基本信息
     *
     * @param id 项目基本信息主键
     * @return 项目基本信息
     */
    @Override
    public Project selectProjectById(Long id) {
        return projectMapper.selectProjectById(id);
    }

    /**
     * 查询项目基本信息列表
     *
     * @param project 项目基本信息
     * @return 项目基本信息
     */
    @Override
    public List<ProjectAndProjectApproval> selectProjectList(String project, String type) {

        return projectMapper.selectProjectAndProjectApprovalList(project, type, getUserId(), true, false);
    }

    /**
     * 新增项目基本信息
     *
     * @param project 项目基本信息
     * @return 结果
     */
    @Override
    public int insertProject(Project project) {
        Project queryProject = new Project();
        queryProject.setIsDelete(false);
        queryProject.setIsEnable(true);
        //判断项目个数是否超过10个
        if (projectMapper.selectProjectList(queryProject).size() > 9) {
            throw new RuntimeException("项目个数限制为10");
        }

        checkAddProject(project);

        Project newProject = new Project();
        newProject.setProjectName(project.getProjectName());
        newProject.setProjectNumber(project.getProjectNumber());
        newProject.setIsDelete(false);
        List<Project> projectsHistory = projectMapper.selectProjectList(newProject);
        if (projectsHistory.size() > 0) {
            throw new RuntimeException("项目名称和编号不可重复");
        }
        project.setCreateTime(DateUtils.getNowDate());
        project.setCreateBy(getUserId());
        //管理员默认是当前登陆人
        project.setAdmin(getUserId());
        int i = projectMapper.insertProject(project);
        if (i > 0) {
            List<Project> projects = projectMapper.selectProjectList(newProject);
            return projects.get(0).getId().intValue();
        }


        return 0;
    }
    /**
     * 修改项目基本信息
     *
     * @param project 项目基本信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProject(Project project) {
        checkUpdateProject(project);

        project.setUpdateTime(DateUtils.getNowDate());
        project.setUpdateBy(getUserId());
        //项目负责人加到项目成员里
        if (project.getAdmin() != null) {
            //修改其他成员角色
            projectMemberMapper.updateProjectMembersRoleByProjectId(project.getId());
            //查出项目成员里是否有他
            ProjectMember projectMember = projectMemberMapper.selectProjectMemberByProjectIdAndUserId(project.getId(), project.getAdmin());
            //有，则修改为项目负责人
            if (projectMember != null) {
                projectMember.setRole(1);
                projectMember.setUpdateTime(DateUtils.getNowDate());
                projectMember.setUpdateBy(getUserId());
                projectMemberMapper.updateProjectMember(projectMember);
            } else {
                //无，则新增
                projectMember = new ProjectMember();
                projectMember.setProjectId(project.getId());
                projectMember.setUserId(project.getAdmin());
                projectMember.setRole(1);
                projectMember.setCreateTime(DateUtils.getNowDate());
                projectMember.setCreateBy(getUserId());
                projectMemberMapper.insertProjectMember(projectMember);
            }
        }
        return projectMapper.updateProject(project);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProjectStatus(ProjectAndProjectApproval project) {
        Project newProject = new Project();
        newProject.setId(project.getId());
        newProject.setStatus(project.getStatus());
        newProject.setUpdateTime(DateUtils.getNowDate());
        newProject.setUpdateBy(getUserId());
        projectMapper.updateProject(newProject);
        if (!ObjectUtils.isEmpty(project.getEnd())) {
            ProjectApproval projectApproval = projectApprovalMapper.selectProjectApprovalByProjectId(project.getId());
            if (projectApproval == null) {
                throw new RuntimeException("项目尚未立项");
            }
            ProjectApproval newProjectApproval = new ProjectApproval();
            newProjectApproval.setId(projectApproval.getId());
            newProjectApproval.setUpdateTime(DateUtils.getNowDate());
            newProjectApproval.setUpdateBy(getUserId());
            newProjectApproval.setEnd(project.getEnd());
            projectApprovalMapper.updateProjectApproval(newProjectApproval);
        }
        return 1;
    }


    /**
     * 批量删除项目基本信息
     *
     * @param ids 需要删除的项目基本信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProjectByIds(Long[] ids) {
        int result = 0;
        //删除项目基本信息
        result += projectMapper.deleteProjectByIds(ids);
        //删除项目立项信息
        result += projectApprovalMapper.deleteProjectApprovalByProjectIds(ids);
        //删除项目人员信息
        result += projectMemberMapper.deleteProjectMemberByProjectIds(ids);
        return result;
    }

    /**
     * 删除项目基本信息信息
     *
     * @param id 项目基本信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProjectById(Long id) {
        int result = 0;
        //删除项目基本信息
        result += projectMapper.deleteProjectById(id);
        //删除项目立项信息
        result += projectApprovalMapper.deleteProjectApprovalByProjectId(id);

        //删除项目人员信息
        result += projectMemberMapper.deleteProjectMemberByProjectId(id);


        return result;
    }

    //项目参数校验
    public boolean checkAddProject(Project project) {
        if (ObjectUtils.isEmpty(project)) {
            throw new RuntimeException("未获取到项目信息");
        }
        if (ObjectUtils.isEmpty(project.getProjectNumber())) {
            throw new RuntimeException("请填写项目编号");
        }
        if (ObjectUtils.isEmpty(project.getProjectName())) {
            throw new RuntimeException("请填写项目名称");
        }
        if (project.getProjectNumber().length() != 24) {
            throw new RuntimeException("项目编号长度必须为24位");
        }
        return true;
    }

    //项目参数校验
    public boolean checkUpdateProject(Project project) {
        if (ObjectUtils.isEmpty(project)) {
            throw new RuntimeException("未获取到项目信息");
        }
        if (ObjectUtils.isEmpty(project.getProjectNumber())) {
            throw new RuntimeException("请填写项目编号");
        }
        if (ObjectUtils.isEmpty(project.getProjectName())) {
            throw new RuntimeException("请填写项目名称");
        }
        if (project.getProjectNumber().length() != 24) {
            throw new RuntimeException("项目编号长度必须为24位");
        }
        if (project.getProjectSource() == null) {
            throw new RuntimeException("请选择项目来源");
        }
        if (project.getProjectType() == null) {
            throw new RuntimeException("请选择项目类型");
        }
        if (StrUtil.isBlank(project.getTechnicalField())) {
            throw new RuntimeException("请填写技术领域");
        }
        if (project.getGeneralBudget() == null) {
            throw new RuntimeException("请填写项目预算");
        }
        if (project.getGovernmentFund() == null) {
            throw new RuntimeException("请填写政府资金");
        }
        if (project.getAdmin() == null) {
            throw new RuntimeException("请选择项目负责人");
        }
        return true;
    }
}
